package edu.winona.csclub.testing.utils;

import java.util.LinkedList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import edu.winona.csclub.testing.core.Range;
import edu.winona.csclub.testing.core.Variable;

public class XmlUtils {
	public static Range getRange(Node chi) {
		Node minNode = chi.getAttributes().getNamedItem("min");
		Node maxNode = chi.getAttributes().getNamedItem("max");
		Node nomNode = chi.getAttributes().getNamedItem("nom");

		int iMin = minNode != null ? Integer.parseInt(minNode.getNodeValue()) : Integer.MIN_VALUE;
		int iMax = maxNode != null ? Integer.parseInt(maxNode.getNodeValue()) : Integer.MAX_VALUE;
		int iNom = nomNode != null ? Integer.parseInt(nomNode.getNodeValue()) : (int)Math.round((iMin + iMax) / 2.0);
		
		return new Range(iMin, iMax, iNom);
	}

	public static LinkedList<Node> getCommands(Element testCase) {
	      IterableNodeList caseKids = new IterableNodeList(testCase.getChildNodes());
	      LinkedList<Node> commands = new LinkedList<Node>();
	      for(Node n : caseKids ){
	    	 if( n.getNodeName().toLowerCase().equals("command")){
	    		 commands.add(n);
	    	 }
	      }
	      return commands;
	}

	public static List<Variable> getVariables(Node command) {
  	List<Variable> variables = new LinkedList<Variable>();
  	
      IterableNodeList commKids = new IterableNodeList(command.getChildNodes());
 	 boolean noVars=true;
 	 
      for(Node n : commKids ){
    	 if( n.getNodeName().toLowerCase().equals("variable")){
    		  // we have a variable!
    		 noVars=false;
    		 String id = n.getAttributes().getNamedItem("id").getNodeValue();
    		 // lets get the Ranges
    		 List<Range> ranges = new LinkedList<Range>();
		      IterableNodeList varKids = new IterableNodeList(n.getChildNodes());
		      for(Node chi : varKids ){
		    	 if( chi.getNodeName().toLowerCase().equals("range")){
		    		ranges.add(XmlUtils.getRange(chi));
		    	 }
		      }
		      if(ranges.size()==0){
		    	  ranges.add(new Range());
		      }
		      // ranges got, now make it into the variable
		      Variable v = new Variable( id,ranges.toArray( new Range[ranges.size()]));
		      variables.add(v);
    	 } 
      }
      
      if(noVars){
    	  
      }
      return variables;
	}
}
